package com.k.rocketmq.demo;

import com.k.rocketmq.RocketMqConst;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.protocol.heartbeat.MessageModel;

import java.util.List;

public class MyConsumer2 {
    public static void main(String[] args) {
        receive();
    }

    private static void receive() {
        System.out.println("消费者2 start");
        String producerGroup = RocketMqConst.CONSUMER_GROUP;
        String namesrvAddr = RocketMqConst.NAME_SRV_ADDR_89;
        String topic = RocketMqConst.COMMAND_TEST_89_TOPIC;
        String tag = RocketMqConst.COMMAND_TEST_89_TOPIC_TAG;
        try {
            // 消费组：不同则都可以收到。消费组相同则一端收到,另一端收不到。还是得根据 集群还是广播确定。
            // 集群消费模式下, 相同Consumer Group的每个Consumer实例平均分摊消息。
            // 广播消费模式下, 相同Consumer Group的每个Consumer实例都接收全量的消息。
            DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(producerGroup);
            //设定消费模式：负载均衡|广播模式  默认为负载均衡
            //负载均衡10条消息，每个消费者共计消费10条
            //广播模式10条消息，每个消费者都消费10条
            consumer.setMessageModel(MessageModel.CLUSTERING);
            //2.指定Nameserver地址
            consumer.setNamesrvAddr(namesrvAddr);
            //3.订阅主题Topic和Tag
            consumer.subscribe(topic, tag);
            // consumer.subscribe("first-topic", "*");
            //consumer.subscribe("base", "Tag1");
            //消费所有"*",消费Tag1和Tag2  Tag1 || Tag2
            //consumer.subscribe("base", "*");
            //4.设置回调函数，处理消息
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                //接受消息内容
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgList, ConsumeConcurrentlyContext context) {
                    for (MessageExt msg : msgList) {
                        System.out.println("消费者2：consumeThread=" + Thread.currentThread().getName() + "," + new String(msg.getBody()));
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            //5.启动消费者consumer
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
        System.out.println("消费者2 finished");
    }
}
